import {baseHost} from '@/setting.js'
const uploadImage = ({
	type,
	imageCompressFn,
	uploadUrl
}) => {
	let _type = type ? type : 'file',
		picFormat = ['jpg', 'png', 'bmp', 'gif', 'jpeg'];

	const formatJudgeSuccess = file => {
		let index = file.lastIndexOf('.'),
			suffix = file.substr(index + 1)
		return picFormat.includes(suffix)
	}

	return new Promise(resolve => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			success(response) {
				
				if (!formatJudgeSuccess(response.tempFilePaths[0])) {
					return uni.showToast({
						title: '文件格式错误！',
						icon: 'none'
					})
				}

				if ((response.tempFiles[0].size / 10485760) >= 10) {
					return uni.showToast({
						title: '图片应小于10MB！',
						icon: 'none'
					})
				}

				imageCompressFn(response.tempFilePaths[0], {
					pixels: 350000, // 最大分辨率，默认二百万
					quality: 0.9, // 压缩质量，默认0.8
					type: 'png', // 图片类型，默认jpg
					canvasId: 'myCanvas',
					base64: false,
				}).then(_res => {
					if (_type === 'file') {
						uni.uploadFile({
							url: uploadUrl || baseHost.car+'/api/common/upload',
							filePath: _res,
							name: 'file',
							success(res) {
								resolve(JSON.parse(res.data).data.url)
							}
						});
					} else if (_type === 'base64') {
						uni.getFileSystemManager().readFile({
							filePath: _res,
							encoding: 'base64',
							success: $res => {
								resolve({
									file: _res,
									base64: $res
								})
							}
						})

					}
				})
			},
			fail(err){
				console.log('用户取消操作')
				uni.hideToast();
			}
		})
	})
}
export default uploadImage
